//
//  OAuthViewController.swift
//  微博Swift
//
//  Created by  justinchou on 16/2/24.
//  Copyright © 2016年  justinchou. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {
    
    // MARK:- 监听方法
    @objc private func dismissVC() {
        navigationController?.dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func autoFill() {
        print("自动填充")
        
        let js = "document.getElementById('userId').value='412528697@qq.com';" +
        "document.getElementById('passwd').value='qwe123';"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    // MARK:- 生命周期
    override func loadView() {
        setupUI()
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
    }
    
    // MARK:- 懒加载
    private lazy var webView: UIWebView = UIWebView()
    
}
// MARK: - UIWebViewDelegate
extension OAuthViewController: UIWebViewDelegate{
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //为何不行？理解错误 request.url是个对象 而absoluteString是一个url的属性
        //因此 request.URL as String 不能达到和实现.absoluteString的功能
        //if let urlString = request.URL as? String
        if let urlString = request.URL?.absoluteString
            where !urlString.hasPrefix(NetworkTools.sharedTools.redirectUri) {
                return true
        }
    
        guard let result = request.URL?.query where result.hasPrefix("code=") else {
            dismissVC()
            // 返回false 不正常执行
            return false
        }
        
        let code = result.substringFromIndex("code=".endIndex)
        print("请求码=\(code)")
        
        NetworkTools.sharedTools.loadAccessToken(code) { (result) -> () in
            
            guard let result = result else {
                print("网络不给力")
                return
            }
            UserAccount.sharedUserAccount.updateUserAccount(result)
            
            //授权成功并且获得用户信息
            NSNotificationCenter.defaultCenter().postNotificationName(JustinLoginSuccessNotification, object: nil)
            
            self.dismissVC()
        }
        
        return false
    }
    
}

// MARK:- 设置界面
extension OAuthViewController {
    private func setupUI() {
        
        view = webView
        
        title = "登录新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "dismissVC")
        navigationItem.leftBarButtonItem?.tintColor = UIColor.orangeColor()
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
    }
}
